<?php
// +----------------------------------------------------------------------
// | 自定义指令
// +----------------------------------------------------------------------
declare(strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\facade\Filesystem;
use PDO;

/**
 * 项目初始化
 *
 * Class ProjInitCommand
 * @package app\command
 */
class ProjInitCommand extends Command
{
    protected function configure()
    {
        $this->setName('init')
            ->setDescription('project init, create .env and database')
            ->addOption('d', null, Option::VALUE_NONE, 'Enable option d');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->info('欢迎使用项目初始化工具！本工具将会引导您配置并创建数据库信息' . PHP_EOL);
        $envPath = '.env';

        if (Filesystem::disk('root')->has($envPath)) {
            $override = $output->confirm($input, '您已执行过初始化，本次操作会覆盖.env文件，是否继续？', true);
            if (!$override) {
                $output->info('已结束运行！');
                return 0;
            }
            //$output->error('You have completed the initialization operation, please do not repeat it.');
            //return 1;
        }

        if ($input->getOption('d')) {
            $config = [
                'name' => 'tp8-server-scaffold',
                'author' => 'myself-private',
                'mysql' => [
                    'host' => '127.0.0.1',
                    'name' => 'tp8-server-scaffold',
                    'user' => 'root',
                    'pass' => '',
                    'port' => '3306',
                    'prefix' => '',
                ]
            ];
        } else {
            $config = [
                'name' => $output->ask($input, '项目名称：', 'tp8-server-scaffold'),
                'author' => $output->ask($input, '您的签名：', 'myself-private'),
                'mysql' => [
                    'host' => $output->ask($input, 'Mysql服务器：', '127.0.0.1'),
                    'name' => $output->ask($input, 'Mysql数据库：', 'tp8-server-scaffold'),
                    'user' => $output->ask($input, 'Mysql用户名：', 'root'),
                    'pass' => $output->ask($input, 'Mysql密码：', ''),
                    'port' => $output->ask($input, 'Mysql端口：', '3306'),
                    'prefix' => $output->ask($input, 'Mysql表前缀：', ''),
                ]
            ];
        }

        try {
            Filesystem::disk('root')->put($envPath, "APP_DEBUG = false

[APP]
NAME = " . $config['name'] . "
SWAGGER_ON = true

[DATABASE]
TYPE = mysql
HOST = " . $config['mysql']['host'] . "
NAME = " . $config['mysql']['name'] . "
USER = " . $config['mysql']['user'] . "
PASS = " . $config['mysql']['pass'] . "
PORT = " . $config['mysql']['port'] . "
CHARSET = utf8
PREFIX = " . $config['mysql']['prefix'] . "

[JWT]
ISSUED_BY = " . $config['author'] . "
PERMITTED_FOR = " . $config['name'] . "
KEY_SECRECT = " . $this->generateRandomKey() . "
EXPIRES_MINUTE = 120
REFRESH_DAY = 7

[SMS]
DEADLINE_MINUTE = 10
INTERVAL_SECOND = 60

DEFAULT_LANG = zh-cn");
            $output->info('已为您生成 .env 文件，您可以随时修改配置信息');
            if (!$input->getOption('d') && $output->confirm($input, '是否需要创建数据库信息（注意：若数据库中已存在数据，本次操作不会覆盖）？', true)) {
                $output->info('正在处理数据库信息...');
                $pdo = new PDO("mysql:host=" . $config['mysql']['host'], $config['mysql']['user'], $config['mysql']['pass']);
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $sql = "CREATE DATABASE IF NOT EXISTS `" . $config['mysql']['name'] . "`";
                $pdo->exec($sql);
                exec('php think migrate:run');
            }
            $output->info('初始化已完成！');
            return 0;
        } catch (\Exception $e) {
            $output->error('An error occurred: ' . $e->getMessage());
            return 1;
        }
    }

    private function generateRandomKey()
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomKey = '';
        for ($i = 0; $i < 32; $i++) {
            $randomKey .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomKey;
    }
}
